classSolution { private: constint BASE = 100007; constint TIMES = 31;
public: intstrStr(string haystack, string needle){ if (needle.empty()) { return0; }
constint needle_size = needle.size(); if (haystack.size() < needle_size) { return-1; } int power = 1; for (int i = 0; i < needle_size; i++) { power = power * TIMES % BASE; }
int needle_code = 0; for (int i = 0; i < needle_size; i++) { needle_code = (needle_code * TIMES + needle[i]) % BASE; }
int code = 0; for (int i = 0; i < haystack.size(); i++) {
// add new code = (code * TIMES + haystack[i]) % BASE; if (i < needle_size - 1) { continue; }
// delete first if (i >= needle_size) { code -= haystack[i - needle_size] * power % BASE; if (code < 0) code += BASE; }
// 其实需要再验证一下 if (code == needle_code) { return (i - needle_size + 1); } }